import { useEffect, useRef, useState } from "react";
import { Button, Card, Drawer, Form, Input, InputNumber, Space, Select, DatePicker, Spin, Tabs } from "antd";
import type { ColumnsType } from "antd/es/table";
import ${businessName}Service, { type PageListReq } from "@/api/services/${moduleName}/${businessName}Service";
import type { ${ClassName} } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
<#if dicts?has_content>
import useDictionary from "@/hooks/system/useDictionary";
import TableDictTag from "@/components/grid/TableDictTag";
</#if>
<#if childrenTables?? && childrenTables?size gt 0>
<#list childrenTables as childTable>
import ${childTable.ClassName}Page, { type ${childTable.ClassName}Handles } from "./${childTable.businessName}";
</#list>
</#if>
import CustomTable from "@/components/grid/CustomTable";

const { TextArea } = Input;

export default function ${ClassName}Page() {
<#if childrenTables?? && childrenTables?size gt 0>
<#list childrenTables as childTable>
    const ${childTable.businessName}Ref = useRef<${childTable.ClassName}Handles>(null);
</#list>
</#if>

    const [loading, setLoading] = useState(false);
    const [submitLoading, setSubmitLoading] = useState(false);
    const [queryParams, setQueryParams] = useState<PageListReq>({
    <#list columns as column>
        <#if column.isQuery()>
      ${column.javaField}: undefined,
        </#if>
    </#list>
      page: 1,
      pageSize: 10,
    });
    const [total, setTotal] = useState(0);
    const [list, setList] = useState<${ClassName}[]>([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [drawerVisible, setDrawerVisible] = useState(false);
    const [editingData, setEditingData] = useState<${ClassName} | null>(null);
    const [form] = Form.useForm();
    const [isView, setIsView] = useState(true);

    //动态设置表格高度
    const [tableScrollY, setTableScrollY] = useState(0);
    const PAGE_OFFSET_HEIGHT = 405;
    const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
    };

    useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
    }, []);

    <#-- 字典项 -->
    <#if dicts??>
        <#list dicts as dict>
    const ${dict.fieldName}Options = useDictionary("${dict.dictCode}");
        </#list>
    </#if>

    <#-- 表格列定义 -->
    const columns: ColumnsType<${ClassName}> = [
    <#list columns as column>
    <#if column.isList()>
    {
      title: "${column.columnComment}",
      width: 120,
      key: "${column.javaField}",
      dataIndex: "${column.javaField}",
    <#if column.dictType?? && column.dictType != "">
      render: (_, record) => (
        <TableDictTag dictCode="${column.dictType}" value={record.${column.javaField} ?? ''}/>
      )
        </#if>
    },
        </#if>
        </#list>
    {
      title: "操作",
      fixed: 'right',
      key: "operation",
      align: "center",
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleView(record)}>
            {t("common.view")}
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            {t("common.edit")}
          </Button>
        </Space>
      ),
    },
    ];

    //加载表格数据
    const fetchPageList = () => {
      setLoading(true);
      ${businessName}Service.pageList(queryParams).then(res => {
         setList(res.records);
         setTotal(res.total);
      }).catch((error) => {
         console.log(error);
         toast.error("获取数据失败！", error);
      }).finally(() => {
            setLoading(false);
      });
    };

    // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
    useEffect(() => {
      fetchPageList();
    }, [queryParams]);

    //选择其他页
    const handlePageChange = (newPage: number, newPageSize: number) => {
      setQueryParams((prev) => ({
        ...prev,
        page: newPage,
        pageSize: newPageSize,
      }));
    };

    //触发编辑按钮
    const handleEdit = (${className}: ${ClassName}) => {
      setEditingData(${className});
      form.setFieldsValue(${className});
      setDrawerVisible(true);
      setIsView(false);
    };

    //触发视图按钮
    const handleView = (${className}: ${ClassName}) => {
      setEditingData(${className});
      form.setFieldsValue(${className});
      setIsView(true);
      setDrawerVisible(true);
    };

    //提交表单数据
    const handleSubmit = async (values:  ${ClassName}) => {
      try {
        setSubmitLoading(true);

<#if childrenTables?? && childrenTables?size gt 0>
<#list childrenTables as childTable>
        //${childTable.functionName}
        const delete${childTable.BusinessName}Ids = ${childTable.businessName}Ref.current?.getDeleteIds();
        const add${childTable.BusinessName}s = ${childTable.businessName}Ref.current?.getAddList();
        const update${childTable.BusinessName}s = ${childTable.businessName}Ref.current?.getUpdateList();

</#list>
</#if>
        const data = {
            ...values,
            id: editingData?.id,
<#if childrenTables?? && childrenTables?size gt 0>
<#list childrenTables as childTable>
            delete${childTable.BusinessName}Ids: delete${childTable.BusinessName}Ids,
            add${childTable.BusinessName}s: add${childTable.BusinessName}s,
            update${childTable.BusinessName}s: update${childTable.BusinessName}s,
</#list>
</#if>
        };
        if (editingData) {
            await ${businessName}Service.update(data);
            toast.success("更新${functionName}成功");
        } else {
            await ${businessName}Service.add(data);
            toast.success("创建${functionName}成功");
        }
        setDrawerVisible(false);
        setEditingData(null);
        form.resetFields();
        fetchPageList();
      } catch (error) {
<#noparse>
        toast.error(`保存失败: ${error.message}`);
</#noparse>
      } finally {
        setSubmitLoading(false);
      }
    };

    const handleDrawerClose = () => {
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
    };

    const handleAdd = () => {
      setEditingData(null);
      form.resetFields();
      setDrawerVisible(true);
      setIsView(false);
    };

    const handleDelete = async () => {
      try {
        setLoading(true);
        await ${businessName}Service.remove(selectedRowKeys);
        toast.success("删除${functionName}成功");
        setSelectedRowKeys([]);
        fetchPageList();
      } catch (error) {
<#noparse>
        toast.error(`删除失败: ${error.message}`);
</#noparse>
      } finally {
        setLoading(false);
      }
    };

    return (
      <Spin spinning={submitLoading} tip="数据提交中..." size="large">
        <Card className="mb-4">
          <Form
            layout="inline"
            style={{ display: "flex", flexWrap: "wrap", gap: "16px" }}
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            onFinish={(values) => {
              setQueryParams((prev) => ({
                ...prev,
                ...values,
                page: 1,
              }));
            }}
          >
            <#list columns as column>
              <#if column.isQuery()>
              <#-- 提前判断字段类型 -->
            <#if column.htmlType??>
              <#assign htmlType = column.htmlType>
            <#else>
              <#assign htmlType = "text">
            </#if>
            <#if column.dictType??>
              <#assign dictTypeLength = column.dictType?length>
            <#else>
              <#assign dictTypeLength = 0>
            </#if>

            <Form.Item
              name="${column.javaField}"
              label="${column.columnComment}"
              style={{ width: 250 }}
              <#if htmlType == "datetime">
                getValueFromEvent={(value) => value ? value.format("YYYY-MM-DD") : null}
                getValueProps={(value) => ({
                  value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
                })}
              </#if>
            >
              <#-- 下拉框（select 类型） -->
              <#if htmlType == "select" && (dictTypeLength > 0)>
              <Select
                options={${column.javaField}Options}
                allowClear
                style={{ width: 170 }}
                placeholder="请选择${column.columnComment}"
              />
              <#-- 日期选择器 -->
              <#elseif htmlType == "date" || htmlType == "datetime">
              <DatePicker
                placeholder="请选择${column.columnComment}"
                style={{ width: 170 }}
              />
              <#-- 默认输入框 -->
              <#else>
                <Input
                  allowClear
                  placeholder="请输入${column.columnComment}"
                />
              </#if>
            </Form.Item>

              </#if>
            </#list>
            <Form.Item style={{ width: 250, marginLeft: 15 }}>
                <Button type="primary" htmlType="submit">
                    查询
                </Button>
                <Button
                  className="ml-2"
                  onClick={() => {
                    setQueryParams({ page: 1, pageSize: 10 });
                  }}
                >
                重置
                </Button>
            </Form.Item>
            </Form>
        </Card>
        <div className="h-4" />
        <Card>
          <CustomTable
                loading={loading}
                columnsConfig={columns}
                dataSource={list}
                total={total}
                selectedRowKeys={selectedRowKeys}
                setSelectedRowKeys={setSelectedRowKeys}
                current={queryParams.page}
                pageSize={queryParams.pageSize}
                onRefresh={fetchPageList}
                onPageChange={handlePageChange}
                selectable
                toolbarButtons={
                    <>
                    <Button type="primary" onClick={handleAdd}>
                        新增
                    </Button>
                    <Button
                        danger
                        disabled={selectedRowKeys.length === 0}
                        onClick={handleDelete}
                    >
                        删除
                    </Button>
                </>
            }
            scroll={{ y: tableScrollY }}
          />
        </Card>
        <Drawer
            title={editingData ? "编辑${functionName}" : "新增${functionName}"}
            width={800}
            open={drawerVisible}
            onClose={handleDrawerClose}
            footer={
                <div className="flex justify-end gap-2">
                    <Button onClick={handleDrawerClose}>取消</Button>
                    {!isView && (
                    <Button type="primary" loading={submitLoading} onClick={() => form.submit()}>
                    确定
                    </Button>
                    )}
                </div>
            }
        >
          <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
            <#list columns as column>
                <#if column.isEdit()>
              <Form.Item
                name="${column.javaField}"
                label="${(column.columnComment)!''}"
                <#if column.isRequired()>
                rules={[
                  {
                    required: true,
                    message: '请填写${column.columnComment}',
                  }
                ]}
                </#if>
                <#if column.htmlType == "datetime">
                getValueFromEvent={(value) => {
                  return value ? value.format("YYYY-MM-DD") : null;
                }}
                getValueProps={(value) => ({
                  value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
                })}
                </#if>
              >
                    <#if column.htmlType == "input">
                        <#if column.javaType == "Integer">
                <InputNumber placeholder="请输入${(column.columnComment)!''}" style={{ width: '100%' }}/>
                        <#else>
                <Input placeholder="请输入${(column.columnComment)!''}" allowClear/>
                        </#if>
                    <#elseif column.htmlType == "select" && column.dictType?? && column.dictType != "">
                <Select options={${column.javaField}Options} allowClear />
                    <#elseif column.htmlType == "checkbox" && column.dictType?? && column.dictType != "">
                <Radio.Group options={${column.javaField}Options} />
                    <#elseif column.htmlType == "datetime">
                <DatePicker
                  style={{width:"100%"}}
                  format="YYYY-MM-DD"
				  onChange={(date) => date ? date.format('YYYY-MM-DD')  : null}
                />
                    <#elseif column.htmlType == "textarea">
                <TextArea/>
                    </#if>
              </Form.Item>

                </#if>
              </#list>
<#if childrenTables?? && childrenTables?size gt 0>
              <Tabs
                  defaultActiveKey="1"
                  items={[
    <#list childrenTables as childTable>
                            {
								key: "${childTable_index + 1}  ",
								label: "${childTable.functionName}",
								children: <${childTable.ClassName}Page ref={${childTable.businessName}Ref} parentId={editingData?.id} />,
							},
    </#list>
                  ]}
              />
</#if>
          </Form>
        </Drawer>
    </Spin>
    );
}
